package com.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.common.constant.ProductConstant;
import com.common.to.SkuReductionTo;
import com.common.to.SpuBoundTo;
import com.common.to.es.SkuEsModel;
import com.common.utils.R;
import com.gulimall.product.dao.AttrDao;
import com.gulimall.product.dao.SpuImagesDao;
import com.gulimall.product.dao.SpuInfoDescDao;
import com.gulimall.product.entity.*;
import com.gulimall.product.feign.CouponFeignService;
import com.gulimall.product.feign.SearchFeignService;
import com.gulimall.product.feign.WareFeignService;
import com.gulimall.product.service.*;
import com.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.mybatis.spring.annotation.MapperScannerRegistrar;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {


    @Autowired
    private SpuInfoDescDao spuInfoDescDao;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoServiceImpl skuInfoService;

    @Autowired
    private SkuImagesServiceImpl skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), new QueryWrapper<SpuInfoEntity>());

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVO vo) {

        // 保存spu基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());

        this.saveBaseInfo(spuInfoEntity);

        // 保存Spu的描述图片
        List<String> decript = vo.getDecript();

        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        this.saveSpuInfoDesc(spuInfoDescEntity);

        // 保存spu图片集
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        // 保存spu的规格参数
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrs.stream().map(attr -> {

            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            AttrEntity attrDB = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrDB.getAttrName());
            productAttrValueEntity.setAttrId(attr.getAttrId());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());

            return productAttrValueEntity;
        }).collect(Collectors.toList());

        productAttrValueService.saveBatch(productAttrValueEntityList);

        // 保存spu的积分信息
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        // 保存 spu的基本信息
        List<Skus> skus = vo.getSkus();
        if (!CollectionUtils.isEmpty(skus)) {
            skus.forEach(sku -> {
                String defaultImg = "";

                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);

                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);

                skuInfoService.save(skuInfoEntity);

                // 保存sku的图片信息
                if (sku.getImages() != null) {
                    List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().filter(image -> image.getImgUrl() != null && !image.getImgUrl().isEmpty()).map(image -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        skuImagesEntity.setImgUrl(image.getImgUrl());
                        skuImagesEntity.setDefaultImg(image.getDefaultImg());

                        if (image.getDefaultImg() == 1) {
                            skuImagesEntity.setImgUrl(image.getImgUrl());
                        }

                        return skuImagesEntity;
                    }).collect(Collectors.toList());

                    skuImagesService.saveBatch(skuImagesEntities);
                }


                // 保存sku的销售属性信息
                List<Attr> attrList = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrList.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());

                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);


                // sku的优惠、满减等信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setMemberPrice(sku.getMemberPrice());
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) > 0) {

                    R r1 = couponFeignService.saveSpuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程调用sku优惠减满失败");
                    }
                }


            });
        }
    }

    @Override
    public void saveSpuInfoDesc(SpuInfoDescEntity spuInfoEntity) {
        spuInfoDescDao.insert(spuInfoEntity);
    }

    @Override
    public void saveBaseInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        // 构造查询条件
        QueryWrapper<SpuInfoEntity> Wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");

        if (StringUtils.isNotBlank(key)) {
            Wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)) {
            Wrapper.and((w) -> {
                w.eq("brand_id", brandId);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)) {
            Wrapper.and((w) -> {
                w.eq("catalog_id", catelogId);
            });
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            Wrapper.and((w) -> {
                w.eq("publish_status", status);
            });
        }

        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), Wrapper);

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {

        // 1、查出当前supId对应的所有sku信息
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        // 查出所有 spu关联的 attr
        List<ProductAttrValueEntity> list = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> ids = list.stream().map(ProductAttrValueEntity::getAttrId).distinct().collect(Collectors.toList());

        List<SkuEsModel.Attrs> attrsList = Optional.ofNullable(attrService.listByIds(ids)).orElse(Collections.emptyList()).stream().filter(attrEntity -> attrEntity.getSearchType() == 1).map(attrEntity -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(attrEntity, attrs1);
            return attrs1;
        }).collect(Collectors.toList());

        // 发送远程·调用是否有库存
        Map<Long, Boolean> collect = null;
        try {
            R skuHasStock = wareFeignService.getSkuHasStock(skuIds);
            TypeReference<List<com.common.to.SkuHasStockVo>> typeReference = new TypeReference<List<com.common.to.SkuHasStockVo>>() {
            };
            List<com.common.to.SkuHasStockVo> data = skuHasStock.getData(typeReference);
            collect = data.stream().collect(Collectors.toMap(com.common.to.SkuHasStockVo::getSkuId, com.common.to.SkuHasStockVo::getHasStock));
        } catch (Exception e) {
            log.error("库存服务查询异常:{}", e);
        }


        // 2.封装每个sku的信息
        Map<Long, Boolean> finalCollect = collect;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            // 组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);

            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            esModel.setHotScore(0L);
            // 设置库存信息
            if (finalCollect == null) {
                esModel.setHasStock(Boolean.TRUE);
            } else {
                esModel.setHasStock(finalCollect.get(esModel.getSkuId()));
            }


            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            if (brandEntity != null) {
                esModel.setBrandName(brandEntity.getName());
                esModel.setBrandImg(brandEntity.getLogo());
            }

            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            if (categoryEntity != null) {
                esModel.setCategoryName(categoryEntity.getName());
            }

            esModel.setAttrs(attrsList);
            return esModel;
        }).collect(Collectors.toList());

        // todo 将数据发送给es进行保存
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode() != 0) {
            // 说明上架失败
        } else {
            // 上架成功
            // todo修改商品的上架状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }
    }
}